﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Tao.Sdl;

namespace Ommf
{
    public class Timer
    {
        private int framerate;
        private double delta = 0;
        private double nextFrame = 0;
        private double frameLength;
        private Stopwatch watch = new Stopwatch();

        internal Timer() : this(60)
        {
            
        }

        internal Timer(int framerate)
        {
            this.framerate = framerate;
            frameLength = 1000.0 / (double)framerate;
        }

        internal void Delay()
        {
            int now = Sdl.SDL_GetTicks();
            while (now < nextFrame)
            {
                Thread.Sleep((int)Math.Round(nextFrame - now));
                now = Sdl.SDL_GetTicks();
            }

            nextFrame = now + frameLength;

            watch.Stop();
            delta = watch.Elapsed.TotalMilliseconds;
            watch.Reset();
            watch.Start();
        }

        internal int FramerateLimit
        {
            get { return framerate; }
            set { framerate = value; frameLength = 1000.0 / (double)framerate; }
        }

        public double Delta
        {
            get { return delta; }
        }

        public int FPS
        {
            get { return (int)((delta > 0) ? 1000 / delta : framerate); }
        }
    }
}
